<template>
  <div>
    <px-button type="primary" class="mr-[8px] mb-[18px]" @click="setGroup">添加设备组</px-button>

    <px-table :data="groupTableData" class="visual-table" size="small" height="calc(100vh - 312px)" border>
      <px-table-column prop="groupName" label="设备组名称" min-width="120" show-overflow-tooltip />
      <px-table-column prop="groupCode" label="设备组Code" min-width="120" show-overflow-tooltip />
      <px-table-column fixed="right" label="操作" min-width="80" align="center">
        <template #default="scope">
          <px-button link @click="editGroupItem(scope.row)">编辑</px-button>

          <px-button link @click="setGroup(scope.row)">重命名</px-button>
          <px-button link type="danger" @click="handleGroupDelete(scope.row)"> 删除 </px-button>
        </template>
      </px-table-column>
    </px-table>
    <px-dialog v-model="groupOpen" :title="!groupNameRow ? '新增设备组名称' : '编辑设备组名称'" width="30%" align-center @close="groupClose">
      <px-form label-width="120px">
        <px-form-item label="分组名称">
          <px-input v-model="groupName" placeholder="填写组名称" />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="groupClose">取消</px-button>
          <px-button type="primary" @click="groupConfirm"> 确认 </px-button>
        </span>
      </template>
    </px-dialog>
    <px-dialog v-model="groupEqpOpen" title="向分组添加设备" width="80%" align-center @close="groupEqpClose">
      <div class="visual-title">{{ groupName }}</div>
      <px-form class="custom-form-ui visual-form" :model="queryParams" label-position="right" label-width="120px">
        <px-button type="primary" class="mr-[8px]" @click="getGroupEqp">添加设备</px-button>
        <px-button type="primary" class="mr-[8px]" @click="seEqpByText">添加设备文本</px-button>
        <px-button type="danger" class="mr-[8px]" @click="delSelectGroupEqp">删除所选设备</px-button>

        <!-- <px-button type="danger" class="mr-[8px]" @click="delAllEqp">清空设备</px-button> -->
        <px-form-item label="设备编号">
          <px-input v-model="queryParams.eqpId" placeholder="请输入设备编号" clearable @keyup.enter="queryTable" />
        </px-form-item>
        <px-button type="primary" @click="queryTable">查询</px-button>
        <px-button @click="resetTable">重置</px-button>
      </px-form>
      <EqpTable
        v-model:queryParams="queryParams"
        :data="groupEqpTableData"
        :eqpImgList="eqpImgList"
        :total="total"
        :needOpt="false"
        @queryTable="queryGroupEqpTable"
        @handleUploadPic="handleUploadPic"
        @handleDelete="handleDelete"
        @selection-change="handleSelectionChange"
        @handle-switch="handleSwitch"
        @handle-switch-liquid="handleSwitchLiquid"
      />
      <px-dialog v-model="groupAddEqpOpen" title="添加设备组设备" width="70%" align-center @close="groupAddEqpClose">
        <EqpTable
          v-model:queryParams="queryParams"
          :data="tableData"
          :total="total"
          :needOpt="false"
          :eqpImgList="eqpImgList"
          @queryTable="queryTable"
          @selection-change="handleSelectionChange"
          @handle-switch="handleSwitch"
          @handle-switch-liquid="handleSwitchLiquid"
        />
        <template #footer>
          <span class="dialog-footer">
            <px-button @click="groupAddEqpClose">取消</px-button>
            <px-button type="primary" @click="groupAddEqpConfirm"> 确认 </px-button>
          </span>
        </template>
      </px-dialog>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="groupEqpClose">关闭</px-button>
        </span>
      </template>
    </px-dialog>
    <px-dialog v-model="eqpTextOpen" title="请粘贴文本" width="30%" align-center @close="eqpTextClose">
      <px-input v-model="eqpText" :rows="30" type="textarea" status="warning" placeholder="Please input" />
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="eqpTextClose">取消</px-button>
          <px-button type="primary" @click="eqpTextConfirm"> 确认 </px-button>
        </span>
      </template>
    </px-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, watch } from "vue";
import { PxMessage, PxMessageBox } from "px-ui";
import {
  listByPositionCode,
  delById,
  groupSaveOrUpdate,
  groupListByPositionCode,
  delGroupItemByNo,
  addEqpsOnGroup,
  updateEqpConfig,
  delGrouoItemByIds
} from "@/api/visual/visualConfig";
import { downloadPic } from "@visual/api/api";
import EqpTable from "./eqpTable.vue";

const props = defineProps({
  treeSelect: {
    type: Object || null
  },

  positionCode: {
    type: String || null
  },
  activeKey: {
    type: String || null
  },
  activeName: {
    type: String || null
  },
  eqpType: {
    type: String || null,
    default: "IFP"
  },
  imgUploadCut: {
    type: Number
  }
});
const emits = defineEmits(["handleUploadPic"]);
const queryParams = ref({
  eqpId: ""
});
const groupTableData = ref([]);
const groupNameRow = ref(null);
const groupOpen = ref(false);
const groupName = ref("");
const currentGroup = ref(null);
const groupEqpTableData = ref([]);
const selectedTable = ref([]);
const eqpImgList = ref({});
const groupEqpOpen = ref(false);
const groupAddEqpOpen = ref(false);
const tableData = ref([]);
const eqpTextOpen = ref(false);
const eqpText = ref("");
const total = ref(0);
watch(
  () => [props.activeKey, props.treeSelect, props.imgUploadCut],
  val => {
    const [activeKey, treeSelect] = val;
    if (activeKey === props.activeName) {
      queryGroupTable();
    }
  }
);
const setGroup = row => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  if (row) {
    groupNameRow.value = row;
    groupName.value = row.groupName;
  } else {
    groupNameRow.value = "";
  }
  groupOpen.value = true;
};
const editGroupItem = row => {
  currentGroup.value = row;
  groupEqpOpen.value = true;
  queryGroupEqpTable();
};
const handleGroupDelete = async row => {
  PxMessageBox.confirm('是否确认删除设备名为"' + row.groupName + '"的数据项？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res = await delGroupItemByNo(row.groupCode);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryGroupTable();
    })
    .catch(() => {});
};
const queryGroupTable = async () => {
  if (props.activeKey !== props.activeName || !props.treeSelect) {
    groupTableData.value = [];
    return;
  }

  const { code: positionCode } = props.treeSelect;

  const data = await groupListByPositionCode({ positionCode, eqpType: props.eqpType });
  if (data) groupTableData.value = data as any[];
};
// 查询设备列表
const queryGroupEqpTable = async () => {
  const { positionCode, groupCode } = currentGroup.value;
  const data = (await listByPositionCode({ positionCode, groupCode, eqpType: props.eqpType })) as any[];

  groupEqpTableData.value = data || [];
  selectedTable.value = [];
  for (let i = 0; i < data?.length; i++) {
    if (data[i].imgName) {
      await getImagByName(data[i].imgName);
    }
  }
};
const getImagByName = async name => {
  if (!name) return;
  if (eqpImgList.value[name]) {
    return eqpImgList.value[name];
  }
  let res = await downloadPic({ originalName: name, moduleName: "twins_visualization" });
  if (res && res[0]) {
    const { fileUrl } = res[0];
    eqpImgList.value[name] = fileUrl;
    return fileUrl;
  }
  return "";
};
const groupConfirm = async () => {
  if (!groupName.value) {
    PxMessage.warning("请填写组名称");
    return;
  }
  const { code: positionCode } = props.treeSelect;
  let saveData: { eqpType: string; positionCode: string; groupName: string; id?: string; groupCode?: string } = {
    positionCode,
    groupName: groupName.value,
    eqpType: props.eqpType
  };
  if (groupNameRow.value) {
    const { id, groupCode } = groupNameRow.value;
    saveData = { ...saveData, id, groupCode };
  }

  const res = await groupSaveOrUpdate(saveData);
  if (res) {
    PxMessage.success(groupNameRow.value ? "编辑组名成功" : "新增组成功");
    queryGroupTable();
    groupClose();
  }
};
const groupClose = () => {
  groupOpen.value = false;
  groupName.value = "";
  groupNameRow.value = "";
};
const groupEqpClose = () => {
  groupEqpOpen.value = false;
};
const getGroupEqp = () => {
  groupAddEqpOpen.value = true;
  queryTable();
  selectedTable.value = [];
};
// 查询设备列表
const queryTable = async () => {
  if (!props.treeSelect) return;
  const params = {
    positionCode: props.treeSelect.code,
    eqpType: props.eqpType,
    ...queryParams.value
  };
  if (!props.treeSelect) {
    return;
  }
  const data = await listByPositionCode(params);

  tableData.value = (data as any[]) || [];
  selectedTable.value = [];
  for (let i = 0; i < data.length; i++) {
    if (data[i].imgName) {
      await getImagByName(data[i].imgName);
    }
  }
};
const delSelectGroupEqp = () => {
  if (!selectedTable.value || selectedTable.value.length === 0) {
    PxMessage.warning("请选择要删除的数据节点");
    return;
  }
  const names = pluck(selectedTable.value, "eqpName");
  PxMessageBox.confirm('是否确认删除名称为"' + names.toString() + "的设备？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const eqpIds = pluck(selectedTable.value, "eqpId");
      const { groupCode } = currentGroup.value;
      const res = await delGrouoItemByIds({ groupCode: null, eqpIds });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      await queryGroupEqpTable();
    })
    .catch(() => {});
};
const seEqpByText = () => {
  if (!props.treeSelect) {
    PxMessage.warning("请选择左树节点");
    return;
  }
  eqpTextOpen.value = true;
};
const eqpTextClose = () => {
  eqpTextOpen.value = false;
  eqpText.value = "";
};
const eqpTextConfirm = async () => {
  if (!eqpText.value) {
    PxMessage.warning("请输入文本");
    return;
  }

  const eqpTextList = eqpText.value.split("\n");
  if (eqpTextList.length > 0) {
    await queryTable();

    selectedTable.value = configureObjectsByStringArray(eqpTextList, tableData.value, "eqpId");
    if (selectedTable.value.length) {
      groupAddEqpConfirm();
    }
  }
  eqpText.value = null;
  eqpTextClose();
};
function configureObjectsByStringArray(stringArray, arrayObjects, key) {
  // 遍历数组对象
  return arrayObjects
    .map(item => {
      // 检查对象是否具有指定的键
      if (item.hasOwnProperty(key)) {
        // 检查字符串数组中是否有与对象键对应的值匹配的项
        if (stringArray.includes(item[key])) {
          // 如果匹配，保留该对象
          return item;
        }
      }
      // 如果不匹配，返回undefined（将被filter掉）
      return undefined;
    })
    .filter(item => item !== undefined); // 过滤掉undefined项
}
function pluck(array, key) {
  return array.map(item => item[key]);
}

const resetTable = () => {
  queryParams.value = {
    eqpId: ""
  };
  queryTable();
};
const handleUploadPic = row => {
  emits("handleUploadPic", row);
};
const handleDelete = async row => {
  PxMessageBox.confirm('是否确认删除设备属性id为"' + row.id + '"的数据项？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const res = await delById(row.id);
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      queryTable();
    })
    .catch(() => {});
};
const handleSelectionChange = datas => {
  selectedTable.value = datas;
};
const groupAddEqpClose = () => {
  groupAddEqpOpen.value = false;
  selectedTable.value = [];
};
const groupAddEqpConfirm = async () => {
  const selectIds = pluck(selectedTable.value, "eqpId");
  if (selectIds.length > 0) {
    const saveData = { groupCode: currentGroup.value.groupCode, eqpIds: selectIds, eqpType: props.eqpType, showAttrInRoom: 0 };
    let res = await addEqpsOnGroup(saveData);
    if (res) {
      PxMessage.success("添加设备成功");

      queryGroupEqpTable();
    } else {
      PxMessage.warning("添加设备失败");
    }
  }
  groupAddEqpClose();
};
async function handleSwitch(row) {
  updateEqpConfigCom(row, "attr");
}
async function handleSwitchLiquid(row) {
  updateEqpConfigCom(row, "liquid");
}
async function updateEqpConfigCom(row, flag) {
  let { id, positionCode, eqpId, groupName, eqpType, showAttrInRoom, showLiquidLevelChange } = row;
  if (flag === "attr" && showAttrInRoom == 1) {
    showLiquidLevelChange = 0;
  } else if (flag === "liquid" && showLiquidLevelChange == 1) {
    showAttrInRoom = 0;
  }
  const res = await updateEqpConfig({ ids: [id], showAttrInRoom, showLiquidLevelChange });
  queryGroupEqpTable();
}
</script>
